import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_jpush/flutter_jpush.dart' ;
import 'package:sy_flutter_alipay/sy_flutter_alipay.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:zhrs/utils/StaticContent.dart';
import 'dart:async';
import 'dart:io';
import '../api/app_context.dart';
import '../api/api.dart';
import '../utils/alert_utils.dart';
import 'face.dart';
import '../service/nfc_reader.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'smart_service.dart';
import 'package:flutter/services.dart';
class IndexPage extends StatefulWidget {
  @override
  IndexPageState createState() => IndexPageState();
}

class IndexPageState extends State<IndexPage> {


    final Completer<WebViewController> _controller =  Completer<WebViewController>();
    String userInfo;
    int _defaultIndex=0;
    BottomItem item_now;
    List<BottomItem> bottomItems;
    List<BottomNavigationBarItem> barItems;
    //AudioRec audioRec;


  @override
  void initState() {
    StaticContent.contexts=context;
    StaticContent.pageState=this;
    /*if(  StaticContent.information!=null)
    {
      new Timer(new Duration(seconds: 1), () {
        // 只在倒计时结束时回调
        alertDialog(context, "通知: "+StaticContent.information);

      });
      //  StaticContent.information=null;
      print("通知内容: "+StaticContent.information);
      // StaticContent.information=null;

    }
     */
    print("init.......");
    super.initState();
    bottomItems=[
      //BottomItem(title: "首页",key:GlobalKey(debugLabel: "home"),icon: Icon(Icons.home),url: "https://www.dzsbk.cn/smartDemo/page/main/dzsbk_xq_06.html",isOffset: false),
      BottomItem(title: "首页",key:GlobalKey(debugLabel: "home"),icon: Icon(Icons.home),url: "https://www.dzsbk.cn/smartDemo/page/main/index.html",isOffset: false),
      BottomItem(title: "发现",key:GlobalKey(debugLabel: "find"),icon: Icon(Icons.find_in_page),url: "https://www.dzsbk.cn/smartDemo/page/explore/index.html"),
      BottomItem(title: "医疗",key:GlobalKey(debugLabel: "his"),icon: Icon(Icons.insert_invitation),url: "https://www.dzsbk.cn/smartDemo/page/medicare/index.html"),
      BottomItem(title: "我的",key:GlobalKey(debugLabel: "my"),icon: Icon(Icons.person),url: "https://www.dzsbk.cn/smartDemo/page/user/index.html"),
      //BottomItem(title: "测试",key:GlobalKey(debugLabel: "test"),icon: Icon(Icons.home),url: "http://106.12.180.103/flutter02.html"),
      //BottomItem(title: "客服",key:GlobalKey(debugLabel: "kefu"),icon: Icon(Icons.contacts),url: "https://demo2.faqrobot.net/robot/h5chat_WD.html?sysNum=15155618951052101&receiveId=&sourceId=30081"),
    ];
    item_now=bottomItems[0];
    barItems=bottomItems.map((item){

      return BottomNavigationBarItem(
          icon: item.icon,
          title: Text(item.title),

      );
    }).toList();

  }

  Onchange(int index,String url)
  {
    if(index>=4)
      return;
    setState(() {
      int beforeindex=_defaultIndex;
      if(_defaultIndex!=index) _defaultIndex=index;

       ///???????????
      if(StaticContent.isonce)
        {
          if(beforeindex==index)
            {
          bottomItems.forEach((item) async{
            if(bottomItems[index]==item&&item.isOffset==true) {
              item_now=item;
              item.isOffset=false;
              //item.webViewController.loadUrl(bottomItems[index].url);
              // item.webViewController.loadUrl(url);
            }
            else
              item.isOffset=true;
          }
          );
            }
        }

      if(StaticContent.isonce==false&&beforeindex==0&&index==0)
        {
          bottomItems.forEach((item) async{
            if(bottomItems[index]==item&&item.isOffset==true) {
              item_now=item;
              item.isOffset=false;
              //item.webViewController.loadUrl(bottomItems[index].url);
              // item.webViewController.loadUrl(url);
            }
            else
              item.isOffset=true;
          }
          );
        }

      bottomItems.forEach((item) async{
        if(bottomItems[index]==item&&item.isOffset==true) {
          item_now=item;
          item.isOffset=false;
          item_now.webViewController.loadUrl(url);

          //item.webViewController.loadUrl(bottomItems[index].url);
         // item.webViewController.loadUrl(url);

        }
        else
          item.isOffset=true;
      }
      );
       });
  }
  //底部选项卡事件
    _onTapBottomItems(index){
      if(_defaultIndex==index) return;
      setState(() {
        _defaultIndex=index;
        bottomItems.forEach((item) async{
          if(bottomItems[index]==item&&item.isOffset==true) {
            item_now=item;
            item.isOffset=false;
            if( await judgeurl())
            {
            }
            else
            {
              /// 在这里重新加载url
              item.webViewController.loadUrl(bottomItems[index].url);

            }


          }
          else
            item.isOffset=true;
        });
      });
    }
   Future<bool>  judgeurl() async
    {
      /*  await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/main/index1.html"||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/main/index2.html"||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/main/index3.html"||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/explore/index1.html" ||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/explore/index2.html" ||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/explore/index3.html" ||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/medicare/index.html" ||
          await item_now.webViewController.currentUrl()== "https://www.dzsbk.cn/smartDemo/page/user/index.html"
     */

      for(BottomItem item in bottomItems)
        {
       if((await item_now.webViewController.currentUrl()).contains(item.url.split(".html")[0]))
         {
           return true;
    }

}
      return false;
    }

  @override
  Widget build(BuildContext context) {

    if(  !StaticContent.isonce)
    {
      new Timer(new Duration(seconds: 1), () {
        // 只在倒计时结束时回调
        //alertDialog(context, "通知: "+StaticContent.information);
        this.Onchange(StaticContent.index, StaticContent.url);
        StaticContent.isonce=true;
      });
    }

      SafeArea safeArea=SafeArea(
        child: new Scaffold(
          body: Stack(
            children: bottomItems.map((item){
              return SafeArea(
                child: Offstage(
                  offstage: item.isOffset,
                  child: WillPopScope(
                      key:GlobalKey(debugLabel: item.title),
                      child: WebView(
                        key:item.key,

                        initialUrl: item.url,
                        javascriptMode: JavascriptMode.unrestricted,
                        onWebViewCreated: (WebViewController webViewController){
                          item.controller??=Completer<WebViewController>();
                          item.webViewController=webViewController;
                          item.webViewController.reload();
                        },
                        javascriptChannels: <JavascriptChannel>[
                          _alertJavascriptChannel(context,item),
                          _appJavascriptChannel(context,item),
                        ].toSet(),
                        navigationDelegate: (NavigationRequest request)  {
                          if (request.url.startsWith('js://webview/queryUser')) {
                            String userInfo =APP.userModel.loginname;
                            item.webViewController.evaluateJavascript(
                                'getUser("$userInfo")')
                                ?.then((result) {
                              print("result:$result");
                            });
                            return NavigationDecision.prevent;
                          }
//                          else if(item.title=='首页'&&request.url.startsWith('https://demo2.faqrobot.net/robot/h5chat_WD.html')){
//                            Navigator.push(context, MaterialPageRoute(builder: (context)=>SmartService(request.url)));
//                          }
                          if(Platform.isAndroid)  SystemChannels.textInput.invokeMethod('TextInput.hide');
                          return NavigationDecision.navigate;
                        },
                        onPageFinished: (String url) {
                          print('Page finished loading: $url');
                        },
                      ),





                      onWillPop: () async{
                        if(Platform.isAndroid)  SystemChannels.textInput.invokeMethod('TextInput.hide');
                        var canGoback= await item_now.webViewController?.canGoBack();
                        if(canGoback){
                          if( await judgeurl())
                            {

                            }
                          else{
                            await item_now.webViewController?.goBack();
                            return Future.value(false);
                          }
                        }
                        else{
                          if( !await judgeurl())
                          {

                            setState(() {
                              item_now.webViewController.loadUrl(bottomItems[_defaultIndex].url);
                              return Future.value(false);
                            });

                          }

                        }

                        Future<bool> canlogout= onWillPop(context);
                        canlogout.then((value){
                          if(value==true) dispose();
                        });
                        return canlogout;
                      }),
                ),
              );
            }).toList(),
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: barItems,
            onTap: _onTapBottomItems,
            currentIndex: _defaultIndex,
            type:BottomNavigationBarType.fixed ,

          ),
        ),
      );


      return safeArea;
  }

  @override
  void dispose() {
    print("logout!!!!!!!!!!!");
    clearCache();
    //if(audioRec!=null) audioRec.stop();
    super.dispose();
  }
  Future<void> clearCache() async{
    bottomItems.forEach((item){
     item.webViewController.clearCache();
    });
  }
  //音频录制
  JavascriptChannel _alertJavascriptChannel(BuildContext context,BottomItem item) {
   // if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel(
        name: 'Recorder',
        onMessageReceived: (JavascriptMessage message) {

          switch(message.message){
            case "start":

              break;
            default:
          }
        });
  }
  //app
  JavascriptChannel _appJavascriptChannel(BuildContext context,BottomItem item) {
    //if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel(
        name: 'App',
        onMessageReceived: (JavascriptMessage message) {
          List<String> mess=message.message.split(":");
          switch(mess[0]){
            case "logout":
              dispose();
              HttpManager.logout(context);
              break;
            case "callScanFace":
              showScanFace(context,mess[1]).then((action){
                item.webViewController.evaluateJavascript(
                    'callScanFaceBackInfo("$action")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "pickImage":
               int iq=60;
               if(mess[2]!=null) iq=int.parse(mess[2]);
               ImagePicker.pickImage(source: mess[1]=='1'?ImageSource.camera:ImageSource.gallery,imageQuality:iq).then((image){
                List<int> list= image.readAsBytesSync();
                String base64Str=base64.encode(list);
                item.webViewController.evaluateJavascript(
                    'pickImageBackInfo("$base64Str")')
                    ?.then((result) {
                  print("result:$result");
                });
               });
              break;
            case "callNFC":
              NfcReader().instance.readSbk().then((result){
                if(result!=null&&result.split(",").length==3){
                  String cardId= NfcReader().instance.resolving(result.split(",")[2]);
                  print("cardId:"+cardId);
                  item.webViewController.evaluateJavascript(
                      'callNFCBackInfo("$cardId")')
                      ?.then((result) {
                    print("result:$result");
                  });
                }
              });
              break;
            case "checkNFC":
              NfcReader().instance.checkNFC().then((result){
                item.webViewController.evaluateJavascript(
                    'checkNFCBackInfo("$result")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "openSmartService":
              Navigator.push(context, MaterialPageRoute(builder: (context)=>SmartService(mess[1]+':'+mess[2])));
              break;
            case "getCurrentPage":
              var title=item_now.title;
              item.webViewController.evaluateJavascript(
                  'getCurrentPageBackInfo("$title")')
                  ?.then((result) {
                print("result:$result");
              });
              break;
            case "hideKeyBoard":
              try {
                if (Platform.isAndroid) SystemChannels.textInput.invokeMethod(
                    'TextInput.hide');
              }catch(e){
                print(e);
              }
              break;
            case "RegistrationID":
              try {
                String RegistrationID=StaticContent.RegistrationID;
                print(RegistrationID);
               if(RegistrationID==null)
                 {
                   FlutterJPush.getRegistrationID().then((String regId) async{
                     StaticContent.RegistrationID=regId;
                   });
                 }

                item.webViewController.evaluateJavascript(
                    'writeRegistrationID("$RegistrationID")')
                    ?.then((result) {
                  print("result:$result");
                });
              }catch(e){
                print(e);
              }
              break;
            case "Alipay":
              try{
                String payInfo=mess[1];
               print(payInfo);
                 SyFlutterAlipay.pay(
                    payInfo,
                    urlScheme: '你的ios urlScheme', //前面配置的urlScheme
                    isSandbox: true //是否是沙箱环境，只对android有效
                ).then((res){
                  payInfo=res.toString();
                  print("结果："+ payInfo);
                  item.webViewController.evaluateJavascript(
                      'writeAlipay(\'$payInfo\')');
                });
              }
              catch(e){
                print(e);
              }
              break;
            case "Signature":
              try{
                alertSignature(context).then((val){

                  if(val!="null")
                    {
                      item.webViewController.evaluateJavascript(
                          'writeSignature(\'$val\')');
                    }

                });
              }
              catch(e){
                print(e);
              }
            break;
            default:
          }
        });
  }
}
Future<String> showScanFace(BuildContext context,String title) async{
   var action = await showDialog(context: context,builder: (context){
    return Scaffold(
      body: Container(
        width: 400.0,
        height: 600.0,
        child:FaceScan(title: title,),
      ),
    );
  });
   return action;
}
class BottomItem{
  final String title;
  final Icon icon;
   bool isOffset;
  final String url;
  Key key;
   Completer<WebViewController> controller;
   WebViewController webViewController;
  BottomItem({this.title,this.icon,this.url,this.isOffset=true,this.key});
}